<?php

	namespace org\tekuna\framework;
	
	use \Exception;

	use org\tekuna\base\Tekuna;

	use org\tekuna\core\application\Application;
	use org\tekuna\core\context\Context;
	use org\tekuna\core\event\Event;
	use org\tekuna\core\event\AbstractEventListener;
	use org\tekuna\core\event\ApplicationRunEvent;
	
	use org\tekuna\framework\request\Request;
	use org\tekuna\framework\request\RequestException;
	use org\tekuna\framework\request\HttpRequestEvent;
	use org\tekuna\framework\request\CliRequestEvent;
	use org\tekuna\framework\context\ContextProcessor;
	use org\tekuna\framework\response\HttpResponseEvent;
	use org\tekuna\framework\response\CliResponseEvent;

		
	class ApplicationRunListener extends AbstractEventListener {

		private $objLogger;


		public function __construct() {

			$this -> objLogger = Tekuna :: getLogger(__CLASS__);
		}

		public function handlesEvent(Event $objEvent) {
			
			return $objEvent instanceof ApplicationRunEvent;
		}
		
		public function handleEvent(Event $objEvent) {
			
			try {
				
				// get the configuration and the root element
				$objConfig = $this -> getApplicationContext() -> getConfiguration();
				$objRootElement = $objConfig -> getRootElement();
	
				// load the additional context values
				$objConP = new ContextProcessor($this -> getApplicationContext());
				$objConP -> updateContext($objRootElement);
	
				// ensure that there is a Request object inside the context
				if (!$this -> getApplicationContext() -> hasRequest() ||
				    !$this -> getApplicationContext() -> getRequest() instanceof Request) {
					
			    	throw new RequestException("No Request object was found in the context.");
				}
				
				// trigger RequestEvent
				if (Application :: isHttpRequest()) {
				
					$objRequestEvent = new HttpRequestEvent($this -> getApplicationContext() -> getRequest());
				}
				else {
					
					$objRequestEvent = new CliRequestEvent($this -> getApplicationContext() -> getRequest());
				}
				
				$this -> getApplicationContext() -> getEventManager() -> triggerEvent($objRequestEvent);

			}
			catch (Exception $objException) {

				// print and log exception messages
				Tekuna :: handleException($objException);
			}
		}
	}